//
//  UrbanMyViewController.m
//  UrbanManagement
//
//  Created by Can on 18/4/8.
//  Copyright © 2018年 hwd. All rights reserved.
//

#import "UrbanMyViewController.h"
#import "UrbanMyTableViewCell.h"
#import "UrbanLogInViewController.h"
#import "UrbanCustomMethod.h"
#import "UrbanRecordingViewController.h"

@interface UrbanMyViewController ()<UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) UIImageView *imageView;//headView
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIImage *headImage;//头像
@property (nonatomic, strong) NSString *number;//多少数据
@property (nonatomic, strong) NSString *clearStr;//缓存大小

@end

@implementation UrbanMyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //头像
    _headImage = [UIImage imageNamed:@"default"];
    
    [self creatView];
    
    [self getNumberRecord];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];

    [self creatClearView];
    
    [self getName];
}

- (void)creatView{
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH - 49) style:UITableViewStylePlain];
    _tableView.backgroundColor = Color(247, 247, 247);
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = 0;
    _tableView.scrollEnabled = NO;
    _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    
    _imageView = [TomamaUI createImageView:CGRectMake(0, 0, SCREENW, 337/2*screenW_6 + 24) backGroundImageV:@"my_bg"];
    [_tableView setTableHeaderView:_imageView];
    _imageView.userInteractionEnabled = YES;
    
    [self creatHeadView];
    
    //退出登录
    CGFloat height = NavBarHeight;
    UIButton *registBtn = [TomamaUI createButton:0 Frame:CGRectMake(15*screenW_6, SCREENH - 15*screenW_6 - 45*screenW_6 - height, SCREENW - 30*screenW_6, 45*screenW_6) targ:self sel:@selector(signOut) titleColor:[UIColor whiteColor] font:[UIFont systemFontOfSize:16*screenW_6] title:@"退出登录" image:nil backGroundImage:@"red_button2"];
    registBtn.layer.cornerRadius = 3*screenW_6;
    registBtn.layer.masksToBounds = YES;
    [self.view addSubview:registBtn];
}

- (void)creatHeadView
{
    //头像
    UIImageView *headPhoto = [[UIImageView alloc]initWithImage:_headImage];
    headPhoto.frame = CGRectMake(0, 40*screenW_6 + 24, 125/2*screenW_6, 125/2*screenW_6);
    headPhoto.layer.cornerRadius = headPhoto.frame.size.width/2;
    headPhoto.layer.masksToBounds = YES;
    [_imageView addSubview:headPhoto];
    headPhoto.center = CGPointMake(_imageView.center.x, headPhoto.center.y);
    
    headPhoto.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chouseIcon)];
    [headPhoto addGestureRecognizer:singleTap];
    
    //姓名
    UILabel *nameLable = [TomamaUI createLabel:CGRectMake(0, CGRectGetMaxY(headPhoto.frame) + 13*screenW_6, SCREENW, 15*screenW_6) textAligment:1 font:[UIFont fontWithName:@"Helvetica-Bold" size:15*screenW_6] textColor:[UIColor whiteColor] text:[Storage getName]];
    [_imageView addSubview:nameLable];
    
    //执法范围
    UILabel *rangeLable = [TomamaUI createLabel:CGRectMake(0, CGRectGetMaxY(nameLable.frame) + 10*screenW_6, SCREENW, 13*screenW_6) textAligment:1 font:[UIFont systemFontOfSize:13*screenW_6] textColor:[UIColor whiteColor] text:[Storage getOfficeName]];
    [_imageView addSubview:rangeLable];
}

- (void)creatClearView
{
    _clearStr = [UrbanCustomMethod getCacheSize];
    [_tableView reloadData];
}

//弹窗提醒框
- (void)signOut
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"确定要注销登录吗？" preferredStyle:  UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [Storage outLogin];
        appDelegate.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[UrbanLogInViewController new]];
    }]];
    [self presentViewController:alert animated:true completion:nil];
}

#pragma mark - tabledelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}

//section头部间距
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 1;
}

//section底部间距
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellID = @"HomeCell";
    UrbanMyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UrbanMyTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    if (indexPath.row == 0) {
        cell.imageV.image = [UIImage imageNamed:@"icon02"];
        cell.titleLable.text = @"历史违法记录";
        cell.msgLable.text = _number;
    }else if (indexPath.row == 1){
        cell.imageV.image = [UIImage imageNamed:@"icon03"];
        cell.titleLable.text = @"清除缓存";
        cell.msgLable.text = _clearStr;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50*screenW_6;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        [self.navigationController pushViewController:[UrbanRecordingViewController new] animated:YES];
    }else if (indexPath.row == 1){//清除缓存
        if ([UrbanCustomMethod clearCaches]){
            [HudHelper hideHudToView:self.view];
            [TomamaUI creatAlertWithTarget:self message:@"清除完成" timeInterval:2];
            
            [self creatClearView];
            
        }else{
            [HudHelper hideHudToView:self.view];
            [TomamaUI creatAlertWithTarget:self message:@"清除失败" timeInterval:2];
        }
    }
}

#pragma mark - @selector
-(void)chouseIcon//添加头像
{
//    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
//    imagePicker.delegate = self;
//    [imagePicker setAllowsEditing:YES];
//    UIAlertController *ac = [UIAlertController alertControllerWithTitle:@"提示" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//    UIAlertAction *a1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//    UIAlertAction *a2 = [UIAlertAction actionWithTitle:@"从相册中选" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;
//        [self presentViewController:imagePicker animated:YES completion:nil];
//    }];
//
//    UIAlertAction *a3 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
//        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) return;
//        [self presentViewController:imagePicker animated:YES completion:nil];
//    }];
//    [ac addAction:a1];
//    [ac addAction:a2];
//    [ac addAction:a3];
//    [self presentViewController:ac animated:YES completion:nil];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"])
    {
        UIImage *image =[info objectForKey:UIImagePickerControllerOriginalImage];

        [self dismissViewControllerAnimated:YES completion:^{
            self->_headImage = image;
            [self->_imageView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
            [self creatHeadView];
        }];
    }
}

- (void)getNumberRecord
{
    NSMutableDictionary *dic = [NSMutableDictionary new];
    [dic setValue:[Storage getToken] forKey:@"user.id"];

    [HttpRequest PostrequestUrl:@"jeesite/appInterface/ZfOrderInfo/queryOrderInfo" Dic:dic completion:^(NSDictionary *responseDic)
     {
         if ([responseDic[@"success"] boolValue]) {//请求成功
             self->_number = [NSString stringWithFormat:@"%@",[responseDic objectForKey:@"count"]];
             [self->_tableView reloadData];
         }else//请求失败提示
         {
             
         }
     }];
}

- (void)getName
{
    NSMutableDictionary *dic = [NSMutableDictionary new];
    [dic setValue:[Storage getToken] forKey:@"userId"];
    [HttpRequest PostrequestUrl:@"jeesite/appInterface/loginInterface/queryUserInfo" Dic:dic completion:^(NSDictionary *responseDic)
     {
        NSLog(@"respond:%@",responseDic);
         if ([responseDic[@"success"] boolValue]) {//请求成功
             
             NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:responseDic[@"userInfo"]];
             [standfault setObject:dic forKey:@"userInfo"];
             [standfault synchronize];
             
             [self->_tableView reloadData];
         }
     }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
